package com.demo.server;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.util.ArrayList;

import com.demo.data.Data;
import com.demo.data.DatabseHandler;
import com.demo.data.Film;

public class ServerThread extends Thread 
{
	private Socket socket;
	private DataInputStream dis;
	private ObjectOutputStream dos;
	private DatabseHandler db;

	public ServerThread(Socket client) 
	{
		socket = client;		
		db = new DatabseHandler();
	}

	public void run() 
	{
		getData();
	}
	public void getData() 
	{
		try 
		{
			Object result = null;
			BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
			int request = Integer.parseInt(br.readLine());
			if(request == Data.REQUEST_LOGIN)
			{
				String[] data = br.readLine().split("/");
				String userName = data[0];
				String password = data[1];
				int resultLogin = requestLogin(userName, password);
				if(resultLogin > 0)
				{
					result = requestGetData();					
				}
			}
			else if(request == Data.REQUEST_ADD_DATA)
			{			
				result = requestAddData();			
			}
			else if(request == Data.REQUEST_UPDATE_DATA)
			{			
				result = requestUpdateData();		
			}
			else if(request == Data.REQUEST_DELETE_DATA)
			{			
				result = requestDeleteData();			
			}
			else if(request == Data.REQUEST_GET_DATA)
			{			
				result = requestGetData();			
			}
			if(request == Data.REQUEST_LOGIN)
			{
				sendDataToClient(request, result, true);	
			}
			else
			{
				sendDataToClient(request, result, false);
			}
			socket.close();
		} 
		catch (IOException e) 
		{
			e.printStackTrace();
		} 		
	}
	public int requestLogin(String userName, String password) 
	{
		return db.login(userName, password);
	}
	public ArrayList<Film> requestGetData() 
	{
		return db.getData();
	}
	public int requestAddData() 
	{
		return db.intsertData(null);
	}
	
	public int requestUpdateData() 
	{
		return db.updateData(null);
	}
	
	public int requestDeleteData() 
	{
		return db.deleteData(null);
	}
	public void sendDataToClient(int request, Object result, boolean isGetdata) 
	{
		if(isGetdata)
		{
			ArrayList<Film> listFilm = (ArrayList<Film>) result;
		}
		else
		{
			
			
		}
		
	}
}
